package cn.kgc.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.kgc.api.entity.Depts;
import cn.kgc.api.entity.Roles;
import cn.kgc.api.entity.Users;
import cn.kgc.api.form.UsersAddForm;
import cn.kgc.api.form.UsersUpdateForm;
import cn.kgc.api.service.DeptsService;
import cn.kgc.api.service.MenusService;
import cn.kgc.api.service.RolesService;
import cn.kgc.api.service.UsersService;
import cn.kgc.api.vo.RouterVo;
import cn.kgc.common.vo.Pager;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kgc
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户模块")
@Validated
@Slf4j
@CrossOrigin
public class UsersController {

    @Resource
    private MenusService menusService;
    @Resource
    private RolesService rolesService;
    @Resource
    private DeptsService deptsService;
    @Resource
    private UsersService usersService;


    @GetMapping("/all")
    @ApiOperation(value = "查询所有用户信息")
    public  List<Users> all(){
        return usersService.list();
    }



    @PostMapping("/delete")
    @ApiOperation(value = "删除用户信息")
    public  boolean delete(@RequestBody HashMap<String,Integer[]> params){
        //1 用户不能删除自己
        //2 部门负责人不能删除



        //获得当前登录的用户ID
        //Integer userId = SystemUtil.getLoginUsers().getUserId();
        //获得删除的用户的ID
        List<Integer> userIds =ListUtil.toList(params.get("userIds"));
//        //如果删除的用户的ID中包含当前登录的用户ID
//        if(userIds.contains(userId)){
//            throw new HttpException(ResultConstant.DELETE_USER_ERROR1);
//        }
//        //如果用户是某个部门的主管,此时不能删除此用户
//        LambdaQueryWrapper<Depts> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Depts::getUserId,userId);
//        int count=deptsService.count(lambdaQueryWrapper);
//        if(count>0){
//            throw new HttpException(ResultConstant.DELETE_USER_ERROR2);
//        }
        return  usersService.removeByIds(userIds);
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取用户的路由信息和权限信息")
    public Map<String, Object> info() {
        Map<String, Object> map = new HashMap<>(2);
        //获得用户的所有路由信息(包含菜单信息)
        List<RouterVo> allRouters = menusService.getAllRouters();
        //获得用户的权限信息
        List<String> buttonPerms = menusService.getButtonPerms();
        map.put("allRouters", allRouters);
        map.put("buttonPerms", buttonPerms);
        return map;
    }

    @PostMapping("/list")
    @ApiOperation("分页查询用户信息")
    public Pager<Users> list(@RequestBody HashMap<String, Object> params) {
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        String userName = params.get("userName").toString();
        String mobile = params.get("mobile").toString();
        int state = Integer.parseInt(params.get("state").toString());
        int deptId = Integer.parseInt(params.get("deptId").toString());
        int roleId = Integer.parseInt(params.get("roleId").toString());
        //分页查询条件
        Page<Users> page = new Page<>(pageNum, pageSize);
        //查询条件
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(StrUtil.isNotBlank(userName), Users::getUserName, userName);
        wrapper.eq(StrUtil.isNotBlank(mobile), Users::getMobile, mobile);
        wrapper.eq(state != 0, Users::getState, state);
        wrapper.eq(deptId != 0, Users::getDeptId, deptId);
        wrapper.eq(roleId != 0, Users::getRoleId, roleId);
        page = usersService.page(page,wrapper);
        List<Users> records = page.getRecords();
        for (Users record : records) {
            //查询角色名字
            Roles role = rolesService.getById(record.getRoleId());
            if (role != null) {
                record.setRoleName(role.getRoleName());
            }
            //查询部门名字
            Depts depts = deptsService.getById(record.getDeptId());
            if (depts != null) {
                record.setDeptName(depts.getDeptName());
            }
            //将查询出来的用户的密码清空
            record.setUserPwd("");
        }
        //返回数据
        return Pager.build(page);
    }

    @PostMapping("/save")
    @ApiOperation(value = "新增用户信息")
    public boolean save(@RequestBody UsersAddForm addForm){
        log.debug("新增用户信息是:{}",addForm);
        Users user = new Users();
        BeanUtil.copyProperties(addForm,user);
        return usersService.save(user);

    }

    @GetMapping("/detail/{id}")
    @ApiOperation(value = "查看用户信息")
    public Users detail(@PathVariable("id") int id){
        Users users = usersService.getById(id);
        users.setUserPwd("");
        return users;
    }

    @PutMapping("/update")
    @ApiOperation(value = "更新用户信息")
    public boolean update(@RequestBody UsersUpdateForm usersUpdateForm){
        log.debug("更新用户信息:{}",usersUpdateForm);
        Integer userId = usersUpdateForm.getUserId();
        Users users = usersService.getById(userId);
        BeanUtil.copyProperties(usersUpdateForm,users);
        return usersService.update(users);
    }

}